import {defineStore} from "pinia";
import myAxios from "../http/myAxios";
import {responseDataHttp} from "../type/response";
import {UserRegFromType} from "../type/Register";
import {showSuccessToast} from "vant";
import router from "../router";
import {loginFromType, loginResponseType} from "../type/login";
import {ref} from "vue";
import {UserInfo, UserInfoRes} from "../type/user";

// 登陆 ，与注册

export const useLoginStore = defineStore('login', () => {

    // 储存用户的信息
    const user = ref<UserInfo>()

    // 注册
    async function register(obj: UserRegFromType) {
        // 创建form-data数据
        const formData = new FormData()
        formData.set("name", obj.username)
        formData.set("account", obj.account)
        formData.set("password", obj.password)
        formData.set("avatar", obj.avatar[0].file as Blob)
        formData.set("sex", obj.sex)
        formData.set("individuality", obj.individuality)

        // 发送请求
        const result = await myAxios<responseDataHttp<{}>>("/user/register", {
            method: "POST",
            data: formData,
        }).then(res => res.data)

        // 判断请求是否发送成功
        if (result.code !== 200) {
            return
        }

        // 注册成功
        showSuccessToast(result.msg);
        router.push({name: "login"})
    }

    // 登陆
    async function login(obj: loginFromType) {
        // 发送请求
        const result = await myAxios<responseDataHttp<loginResponseType>>("/user/login", {
            method: "POST",
            headers: {
                'Content-Type': 'application/json'
            },
            data: JSON.stringify({
                "account": Number(obj.username),
                "password": obj.password
            })
        }).then(r => r.data)

        // 判断请求是否发送成功
        if (result.code !== 200) {
            return
        }

        // 注册成功
        // 储存token
        localStorage.setItem("token", result.data.token)
        showSuccessToast(result.msg);
        await router.push({name: "home"})
        // 刷新页面
        location.reload()
    }

    // 验证token  获取用户 信息
    async function getUserInfo() {
        // 判断是否存在token,如果不存在则退出
        if (localStorage.getItem("token")==null||localStorage.getItem("token")==undefined){
            return
        }

        // 使用 myAxios 向服务器请求数据 responseDataHttp是服务器返回的数据 await是让浏览器读取信息 <UserInfoRes>是服务器返回的数据
        const result = await myAxios<responseDataHttp<UserInfoRes>>("/user/verify", {
            method: "GET"
        }).then(r => r.data)
        // 获取到服务器的数据
        // user是自己声明的一个仓库， result是服务器返回的数据。data是服务器返回的对象，将后端user的值赋给自己声明的仓库
        user.value = result.data.user
    }

    return {
        user,
        register,
        login,
        getUserInfo
    }
})